import axios from 'axios';
import storage from 'store';
import { diffTokenTime } from '@/utils/auth';

var base = '';  //  声明的地址
// 开发环境 http://xuexi.bzszxr.com/
console.log(process.env)  //  http://192.168.1.146:9001/bzsz
if(process.env.NODE_ENV == 'development'){       // 本地/开发环境
  base = 'http://192.168.110.239:9001/bzsz';
}else if(process.env.NODE_ENV == 'production'){  // 生产环境或者叫做线上的环境
  base = 'http://xuexi.bzszxr.com/bzsz';
}else {   // 测试环境
  // base = 'http://test.bzszxr.com/bzsz';
  base = 'http://admin-test.bzszxr.com/bzsz'
};
axios.defaults.timeout = 6000;    // 请求超时时间1分钟
axios.defaults.baseURL = base;    // 你的接口地址
axios.defaults.responseType = "json";
axios.defaults.withCredentials = true;  //是否允许带cookie这些

const Axios = axios.create({
  baseURL: '/api', //process.env.VUE_APP_BASE_API
  timeout: 6000,
  // withCredentials: true, // 允许跨域
  // `headers` 是即将被发送的自定义请求头
  // headers: {'X-Requested-With': 'XMLHttpRequest'},
  // headers: {'X-Custom-Header': 'foobar'}
})
// axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
axios.defaults.headers['Content-Type'] = 'application/x-www-form-urlencoded';
// axios.defaults.headers['Content-Type'] = 'multipart/form-data';
// axios.defaults.headers['Content-Type'] = 'application/json';
// axios.defaults.headers['Content-Type'] = 'text/xml';

// 引入饿了么组件
import { Message, Loading } from 'element-ui';
import qs from 'qs';

let loading;
let loadingNum = 0;  //  内存中正在请求的数量

function startLoading() {
  if(loadingNum == 0) {
    loading = Loading.service({
      lock: true,
      text: '拼命加载中...',
      background:'rgba(255,255,255,1)',
      spinner: 'el-icon-loading',
      target: document.querySelector('.content')
    })
  }
  loadingNum++;
}

function endLoading() {  //  关闭加载动画
  loadingNum--;
  if(loadingNum <= 0) {
      loading.close();
  }
}

// 请求拦截器
Axios.interceptors.request.use( response => {
  // console.log(response)
  // startLoading();  // 打开loading加载动画
  const token = storage.get('logintoken');  // 获取登录时存储的token
  if(token) {
    response.headers['Authorization'] = token;
  }
  return response;
}, (error) => {
  return Promise.reject(error);
})

// 响应连接器
Axios.interceptors.response.use( response => {
  // console.log(response)
  // endLoading(); // 关闭loading加载动画
  const data = response.data;
  if(response.config.method === 'post'){
    response.data = qs.stringify({...response.data});
  }
  switch (data.code) {  // switch语句中可以使用return代替break
    case 200 || 201:
      return data
    case 401:
      router.push({ path: "/login" });
      window.location.reload();
      Message({ message: '登录信息已过期,请重新登录', type: 'warning' });
      break;
    case 403:
      if(data.errorMessage != null) {
        Message({ message: data.errorMessage, type: 'warning' });
      } else {
        Message({ message: '未知错误', type: 'warning' });
      }
      break;
    case 404:
      if(data.errorMessage != null) {
        Message({ message: data.errorMessage, type: 'warning' });
      } else {
        Message({ message: '未知错误', type: 'warning' });
      }
      break;
    case 500:
      if(data.errorMessage != null) {
        Message({ message: data.errorMessage, type: 'warning' });
      } else {
        Message({ message: '未知错误', type: 'warning' });
      }
      break
    default:
      return data
  }
}, (error) => {
  // endLoading(); // 关闭loading加载动画
  return Promise.reject(error);
})

// 登录请求方法
const loginreq = (method, url, params) => {
    return axios({
        method: method,
        url: url,
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
        },
        data: params,
        traditional: true,
        transformRequest: [
            function(data) {
                let ret = ''
                for (let it in data) {
                    ret +=
                        encodeURIComponent(it) +
                        '=' +
                        encodeURIComponent(data[it]) +
                        '&'
                }
                return ret
            }
        ]
    }).then(res => res.data);
};
// // 通用公用方法
const req = (method, url, params) => {
    return axios({
        method: method,
        url: url,
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
          token: localStorage.getItem('logintoken')
        },
        data: params,
        traditional: true,
        transformRequest: [
            function(data) {
                let ret = ''
                for (let it in data) {
                    ret +=
                        encodeURIComponent(it) +
                        '=' +
                        encodeURIComponent(data[it]) +
                        '&'
                }
                return ret
            }
        ]
    }).then(res => res.data);
};

// // 封装delete请求
// const del = (url, data) => {
//   return Axios({
//     url: url,
//     method: 'delete',
//     headers: { 'Content-type': 'application/x-www-form-urlencoded;charset=UTF-8' },
//     data: qs.stringify(data)
//   })
// }

export {
  loginreq,
  req,
  // del,
  base,
  Axios
}
